<template>
  <div class="category-container">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <span>我的训练记录</span>
          <el-radio-group v-model="statusFilter" @change="handleStatusFilterChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="scheduled">已安排</el-radio-button>
            <el-radio-button label="completed">已完成</el-radio-button>
            <el-radio-button label="missed">未通过</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <!-- 添加加载状态 -->
      <div v-loading="loading">
        <el-table :data="filteredTrainings" style="width: 100%" border>
          <el-table-column label="序号" width="80">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>

          <el-table-column prop="date" label="日期" width="150" sortable>
            <template #default="scope">
              <div class="date-cell">
                {{ formatDate(scope.row.start_time) }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="time" label="时间" width="120">
            <template #default="scope">
              {{ formatTimeRange(scope.row.start_time, scope.row.end_time) }}
            </template>
          </el-table-column>

          <el-table-column prop="coach" label="教练" width="120" />

          <el-table-column prop="program" label="训练项目" min-width="200" />

          <el-table-column prop="status" label="状态" width="120" sortable>
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleViewDetails(scope.row)"
              >
                详情
              </el-button>
              <!-- 已完成的训练可以评价或查看评价 -->
              <el-button
                v-if="scope.row.status === 'COMPLETED'"
                size="small"
                :type="scope.row.hasFeedback ? '' : 'primary'"
                :disabled="scope.row.hasFeedback"
                @click="scope.row.hasFeedback ? viewFeedback(scope.row) : handleFeedback(scope.row)"
              >
                {{ scope.row.hasFeedback ? '已评价' : '评价' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          class="pagination"
          v-model:current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="totalTrainings"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 训练详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="训练详情" width="60%">
        <div v-if="selectedTraining" class="training-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="训练编号">
              {{ selectedTraining.id }}
            </el-descriptions-item>
            <el-descriptions-item label="训练项目">
              {{ selectedTraining.program }}
            </el-descriptions-item>
            <el-descriptions-item label="教练">
              {{ selectedTraining.coach }}
            </el-descriptions-item>
            <el-descriptions-item label="日期">
              {{ formatDate(selectedTraining.start_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="时间">
              {{ formatTimeRange(selectedTraining.start_time, selectedTraining.end_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(selectedTraining.status)">
                {{ getStatusText(selectedTraining.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDateTime(selectedTraining.create_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="反馈内容">
              {{ selectedTraining.content || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="教练回复">
              {{ selectedTraining.response || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 评价对话框 -->
      <el-dialog v-model="feedbackDialogVisible" :title="viewingFeedback ? '查看评价' : '训练评价'" width="60%">
        <div v-if="feedbackTraining" class="feedback-form">
          <el-form :model="feedbackForm" label-width="100px" @submit.prevent>
            <el-form-item label="训练项目">
              <el-input v-model="feedbackTraining.program" readonly />
            </el-form-item>
            <el-form-item label="教练">
              <el-input v-model="feedbackTraining.coach" readonly />
            </el-form-item>
            <el-form-item label="训练时间">
              <el-input :value="`${formatDate(feedbackTraining.start_time)} ${formatTimeRange(feedbackTraining.start_time, feedbackTraining.end_time)}`" readonly />
            </el-form-item>
            <el-form-item label="评分" :required="!viewingFeedback">
              <el-rate
                v-model="feedbackForm.rating"
                :max="5"
                :allow-half="false"
                :show-text="true"
                :texts="['很差', '较差', '一般', '良好', '优秀']"
                :disabled="viewingFeedback"
              />
            </el-form-item>
            <el-form-item label="训练反馈" :required="!viewingFeedback">
              <el-input
                v-model="feedbackForm.feedback"
                type="textarea"
                :rows="4"
                :readonly="viewingFeedback"
                :placeholder="viewingFeedback ? '' : '请输入您的训练反馈...'"
              />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="feedbackDialogVisible = false">关闭</el-button>
            <el-button v-if="!viewingFeedback" type="primary" @click="submitFeedback">提交</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import requestUtil from '@/util/request.js'

// 数据和状态
const trainings = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10) // 固定每页10条
const statusFilter = ref('all')

// 学生ID（需要从实际用户信息中获取）
const studentId = ref('')

// 对话框
const detailDialogVisible = ref(false)
const selectedTraining = ref(null)

const feedbackDialogVisible = ref(false)
const feedbackTraining = ref(null)
const viewingFeedback = ref(false) // 是否查看评价模式
const feedbackForm = reactive({
  rating: 5,
  feedback: ''
})

// 分页和过滤
const filteredTrainings = computed(() => {
  let result = [...trainings.value]

  // 状态过滤
  if (statusFilter.value !== 'all') {
    result = result.filter(item => item.status.toLowerCase() === statusFilter.value)
  }

  // 分页
  return result.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
})

const totalTrainings = computed(() => {
  let result = trainings.value

  if (statusFilter.value !== 'all') {
    result = result.filter(item => item.status.toLowerCase() === statusFilter.value)
  }

  return result.length
})

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleStatusFilterChange = () => {
  currentPage.value = 1
}

// 状态处理 - 根据后端模型调整
const getStatusType = (status) => {
  // 统一转换为大写进行比较
  const statusValue = status?.toUpperCase()
  switch (statusValue) {
    case 'SCHEDULED':
      return 'warning'
    case 'COMPLETED':
      return 'success'
    case 'CANCELED':
      return 'info'
    case 'MISSED':
      return 'danger'
    default:
      return ''
  }
}

const getStatusText = (status) => {
  // 统一转换为大写进行比较
  const statusValue = status?.toUpperCase()
  switch (statusValue) {
    case 'SCHEDULED':
      return '已安排'
    case 'COMPLETED':
      return '已完成'
    case 'CANCELED':
      return '已取消'
    case 'MISSED':
      return '已错过'
    default:
      return status
  }
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 日期时间格式化
const formatDateTime = (dateString) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 时间范围格式化
const formatTimeRange = (startTime, endTime) => {
  try {
    if (!startTime || !endTime) return '--:--'

    // 处理时间格式
    const formatTime = (timeValue) => {
      if (!timeValue) return '--:--'

      // 如果是字符串格式的时间
      if (typeof timeValue === 'string') {
        if (timeValue.includes('T')) {
          // ISO格式时间
          const date = new Date(timeValue)
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          return `${hours}:${minutes}`
        } else if (timeValue.includes(':')) {
          // 时间格式 HH:MM:SS 或 HH:MM
          const parts = timeValue.split(':')
          return `${parts[0]}:${parts[1]}`
        }
      }
      // 如果是Date对象
      else if (timeValue instanceof Date) {
        const hours = String(timeValue.getHours()).padStart(2, '0')
        const minutes = String(timeValue.getMinutes()).padStart(2, '0')
        return `${hours}:${minutes}`
      }
      // 如果是时间戳
      else if (typeof timeValue === 'number') {
        const date = new Date(timeValue)
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${hours}:${minutes}`
      }

      return '--:--'
    }

    return `${formatTime(startTime)}-${formatTime(endTime)}`
  } catch (error) {
    console.error('格式化时间出错:', error)
    return '--:--'
  }
}

// 对话框操作
const handleViewDetails = (training) => {
  selectedTraining.value = training
  detailDialogVisible.value = true
}

// 查看评价
const viewFeedback = (training) => {
  feedbackTraining.value = training
  feedbackForm.rating = training.rating || 5
  feedbackForm.feedback = training.feedback || ''
  viewingFeedback.value = true
  feedbackDialogVisible.value = true
}

// 评价操作
const handleFeedback = (training) => {
  feedbackTraining.value = training
  feedbackForm.rating = 5
  feedbackForm.feedback = ''
  viewingFeedback.value = false
  feedbackDialogVisible.value = true
}

// 提交评价
const submitFeedback = async () => {
  if (!feedbackTraining.value) return

  try {
    const res = await requestUtil.put(`/student_training/trainings/update/${feedbackTraining.value.id}`, {
      rating: feedbackForm.rating,
      feedback: feedbackForm.feedback,
      // 保持其他字段不变，但确保状态值是大写
      student_id: feedbackTraining.value.student_id,
      coach_id: feedbackTraining.value.coach_id,
      program_id: feedbackTraining.value.program_id,
      start_time: feedbackTraining.value.start_time,
      end_time: feedbackTraining.value.end_time,
      status: feedbackTraining.value.status.toUpperCase(), // 转换为大写
      content: feedbackTraining.value.content,
      response: feedbackTraining.value.response,
    })

    if (res.data?.status === 200) {
      ElMessage.success('评价提交成功')
      feedbackDialogVisible.value = false
      // 更新本地数据
      const index = trainings.value.findIndex(t => t.id === feedbackTraining.value.id)
      if (index !== -1) {
        trainings.value[index].hasFeedback = true
        trainings.value[index].rating = feedbackForm.rating
        trainings.value[index].feedback = feedbackForm.feedback
      }
    } else {
      ElMessage.error(res.data?.message || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交评价失败: ' + (error.message || '未知错误'))
    console.error('提交评价失败:', error)
  }
}

// 获取用户ID
const getUserId = () => {
  try {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('user_info')

    if (userInfo) {
      // 如果存储的是JSON字符串，需要解析
      const user = JSON.parse(userInfo)
      return user.user_id || user.id || user.userId
    }

    // 如果user_info不存在，尝试直接获取user_id
    return localStorage.getItem('user_id')
  } catch (error) {
    console.error('解析用户信息失败:', error)
    // 出错时返回直接存储的user_id
    return localStorage.getItem('user_id')
  }
}

// 获取训练数据
const fetchTrainings = async () => {
  // 获取学生ID
  studentId.value = getUserId()

  // 检查是否有学生ID
  if (!studentId.value) {
    ElMessage.warning('未获取到用户信息，请重新登录')
    return
  }

  loading.value = true
  try {
    // 使用requestUtil调用API
    const response = await requestUtil.get(`/student_training/trainings/user/${studentId.value}`)

    // 打印响应数据以便调试
    console.log('训练记录响应数据:', response.data)

    // 根据实际返回的数据结构处理数据
    if (response.data && response.data.data) {
      // 提取实际的训练数据并转换为前端需要的格式
      const rawData = response.data.data

      // 转换数据格式以匹配前端组件的需求
      trainings.value = rawData.map(item => {
        // 确保状态值是大写的
        const status = item.status?.toUpperCase() || 'UNKNOWN'

        return {
          id: item.training_id,
          start_time: item.start_time,
          end_time: item.end_time,
          coach: item.coach_name,
          program: item.program_name,
          status: status,
          create_at: item.create_at,
          content: item.content || '',
          response: item.response || '',
          feedback: item.feedback || '',
          notes: item.notes || '',
          hasFeedback: !!item.feedback, // 是否已有反馈
          rating: item.rating || 0,
          student_id: item.student_id,
          coach_id: item.coach_id,
          program_id: item.program_id
        }
      })
    } else {
      // 如果没有数据，设置为空数组
      trainings.value = []
      ElMessage.info('暂无训练记录')
    }
  } catch (error) {
    ElMessage.error('获取训练信息失败: ' + (error.message || '未知错误'))
    console.error('获取训练信息失败:', error)
    trainings.value = [] // 设置为空数组以避免后续错误
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  // 获取训练数据
  fetchTrainings()
})
</script>

<style lang="scss" scoped>
.category-container {
  padding: 20px 0;

  .category-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }

  .date-cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
  }

  .training-detail {
    padding: 10px;
  }

  .feedback-form {
    padding: 10px;
  }

  .dialog-footer {
    text-align: right;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: stretch;
    }

    .el-table th,
    .el-table td {
      padding: 8px 4px;
    }
  }
}
</style>
